import { LoginResponse, Token } from '@/types/data';
import { http } from '@/utils/http';
import { cleartoken, setToken } from '@/utils/token';
import { createSlice } from '@reduxjs/toolkit';
import { createAsyncThunk } from '@reduxjs/toolkit';
// 错误类型
import type { AxiosError } from 'axios';

// 登录
export const login = createAsyncThunk(
  'login/login',
  async (
    data: { mobile: '13718451179'; code: '123456' },
    { rejectWithValue }
  ) => {
    try {
      const res = await http.post<LoginResponse>('/authorizations', data);
      // 保存在本地
      setToken(res.data.data);
      // 保存在redux
      return res.data.data;
    } catch (e) {
      const error = e as AxiosError<{ data: null; message: string }>;
      return rejectWithValue(error.response?.data);
    }
  }
);
// 发送验证码
export const getCode = createAsyncThunk(
  'login/send',
  async (mobile: string) => {
    await http.get(`/sms/codes/${mobile}`);
  }
);
// 登录退出功能
export const logout = createAsyncThunk('login/logout', () => {
  // 清除本地token
  cleartoken();
  // 清除redux里的token
  return initialState;
});

const initialState: Token = {
  token: '',
  refresh_token: '',
};

const loginredu = createSlice({
  name: 'login',
  initialState,
  reducers: {
    updateToken: (state, action) => {
      return action.payload;
    },
  },
  // 额外的reducers
  extraReducers: (builder) => {
    builder.addCase(login.fulfilled, (state, action) => {
      return action.payload;
    });
    builder.addCase(logout.fulfilled, (state, action) => {
      return action.payload;
    });
  },
});
export const { updateToken } = loginredu.actions;
export default loginredu.reducer;
